﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using DevExpress.Utils;
using LHS.Core.CaseRecord.Classes;
using DevExpress.XtraEditors.Controls;
using Padding = DevExpress.XtraLayout.Utils.Padding;
using LHS.Core.TableInfo.SetUpCaseRecordForm;
using DevExpress.XtraTreeList;
using LHS.Core.CaseRecord.Controller;
using MS.Core.Base.Transaction;
using MS.Core.Base.Data;
using MS.Core.Constants;
using LHS.Core.TableInfo;
using System.Collections.Specialized;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraTab;

namespace LHS.Win.SetUpCaseRecordForm.Forms
{
    public partial class frmBieuMau_1 : Form
    {
        #region constructor
        public frmBieuMau_1(Form frmCaller, String strCategoryID, String strPatientID, String strOtherID1, String strOtherID2, String strOtherID3, clsEnumType.DisplayMode eDisplayMode)
        {
            InitializeComponent();

            this._frmCaller = frmCaller;
            this._strPreCategoryID = strCategoryID;
            this._strCategoryID = strCategoryID;
            this._strPatientID = strPatientID;
            this._strOtherID1 = strOtherID1;
            this._strOtherID2 = strOtherID2;
            this._strOtherID3 = strOtherID3;
            this._eDisplayMode = eDisplayMode;
            _setDisplayControl(this._eDisplayMode);
        }
        #endregion

        #region variables
        clsEnumType.DisplayMode _eDisplayMode = clsEnumType.DisplayMode.PREVIEW;
        private Form _frmCaller;

        private String _strPreCategoryID = "";
        private String _strCategoryID = "";
        private String _strPatientID = "";
        private String _strOtherID1 = "";
        private String _strOtherID2 = "";
        private String _strOtherID3 = "";

        private DataSet _dsDynamicTable;
        private DataTable _dtCaseRecord_Category;
        private DataTable _dtCaseRecord_Tree;
        private DataTable _dtCaseRecord_Leaf;
        private DataTable _dtDynamicTable;
        private DataRow _drDynamicRow;
        private String _strTableName = "";
        private int _maxLevel = 0;
        private Boolean _blnFirstLoad = true;
        #endregion

        #region properties
        private CaseRecordController caseRecordController;
        private CaseRecordController _caseRecordController
        {
            get
            {
                if (caseRecordController == null)
                    caseRecordController = new CaseRecordController();
                return caseRecordController;
            }
        }
        #endregion

        #region controls events
        private void frmBieuMau_Load(object sender, EventArgs e)
        {
            try
            {
                if (this._frmCaller != null)
                {
                    if (this._frmCaller is frmMain)
                    {
                        this.Width = this._frmCaller.Width * 80 / 100;
                        this.Height = this._frmCaller.Height * 80 / 100;
                        this.Left = (this._frmCaller.Width - this.Width) / 2;
                        this.Top = (this._frmCaller.Height - this.Height) / 4;
                    }
                    else
                    {
                        this.Width = this._frmCaller.Width;
                        this.Height = this._frmCaller.Height;
                        this.Left = this._frmCaller.Left;
                        this.Top = this._frmCaller.Top;
                    }
                }

                this.btnSave.Enabled = this.btnDelete.Enabled = false;
                if (this._eDisplayMode != clsEnumType.DisplayMode.STATISTICAL)
                    _getData();
            }
            catch (Exception ex) { Class.ShowException(ex); }
        }

        private void frmBieuMau_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (this._frmCaller != null && this._frmCaller is frmMain)
                    ((frmMain)this._frmCaller).mnuBaoCao_ThongKePhauThuat.Enabled = true;
            }
            catch (Exception ex) { Class.ShowException(ex); }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                TransactionManager.ThreadTransactionMgr().BeginTransaction();
                this._caseRecordController.insertUpdateDynamicTable(this._dtCaseRecord_Category.Rows[0][CaseRecord_CategoryInfo.CRC_ID].ToString(), _dtDynamicTable);
                TransactionManager.ThreadTransactionMgr().CommitTransaction();
                MessageBox.Show(clsConstant.MSG_SaveSuccessful);
            }
            catch (Exception ex)
            {
                TransactionManager.ThreadTransactionMgr().RollbackTransaction();
                Class.ShowException(ex);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show(clsConstant.MSG_ConfirmDeleteData, this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                    {
                        TransactionManager.ThreadTransactionMgr().BeginTransaction();
                        this._caseRecordController.deleteDynamicTable(this._strCategoryID, this._dtDynamicTable);
                        TransactionManager.ThreadTransactionMgr().CommitTransaction();
                    }
                    MessageBox.Show(clsConstant.MSG_DeleteSuccessful);
                    this._getData();
                }
            }
            catch (Exception ex)
            {
                TransactionManager.ThreadTransactionMgr().RollbackTransaction();
                Class.ShowException(ex);
                _getData();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnStatistical_Click(object sender, EventArgs e)
        {
            try
            {
                this._drDynamicRow[clsDynamicTable.Surgical_Reason] = this.txtStatistical_LyDoPT.Text.Trim();
                String strSurgical_DateFrom = "";
                String strSurgical_DateTo = "";
                if (chkStatistical_NgayPT.Checked)
                {
                    strSurgical_DateFrom = dateStatistical_NgayPT_From.EditValue.ToString();
                    strSurgical_DateTo = dateStatistical_NgayPT_To.EditValue.ToString();
                }
                DataTable dtResult = this._caseRecordController.getStatisticalDataDT(this._dsDynamicTable, strSurgical_DateFrom, strSurgical_DateTo);
                if (dtResult.Rows.Count > 0)
                {
                    frmKetQuaThongKe ketQuaThongKe = new frmKetQuaThongKe(dtResult);
                    ketQuaThongKe.ShowDialog();
                }
                else
                {
                    MessageBox.Show(clsConstant.MSG_Statistical_NotFound);
                }
            }
            catch (Exception ex)
            {
                Class.ShowException(ex);
            }
        }

        private void dteBenhNhan_NgayPT_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[clsDynamicTable.Surgical_Date] = dteBenhNhan_NgayPT.EditValue;
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }

        private void txtBenhNhan_LyDoPT_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[clsDynamicTable.Surgical_Reason] = txtBenhNhan_LyDoPT.Text;
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }

        private void cboLoaiBieuMau_EditValueChanged(object sender, EventArgs e)
        {
            this._strCategoryID = this.cboLoaiBieuMau.EditValue.ToString();
            if (this._strCategoryID != "-1")
            {
                _getData();
                this._blnFirstLoad = false;
            }
        }

        private void chkStatistical_NgayPT_EditValueChanged(object sender, EventArgs e)
        {
            this.dateStatistical_NgayPT_From.Enabled = this.dateStatistical_NgayPT_To.Enabled = this.chkStatistical_NgayPT.Checked;
        }
        #endregion

        #region private functions
        private void _getData()
        {
            DataTable dtPatient = this._caseRecordController.getPatientDT(this._strPatientID);
            if (dtPatient.Rows.Count > 0)
            {
                this.txtBenhNhan_DiaChi.Text = dtPatient.Rows[0][InfoPatients.PATADDRESS].ToString();
                this.txtBenhNhan_DiDong.Text = dtPatient.Rows[0][InfoPatients.PATMOBILE].ToString();
                this.txtBenhNhan_DTnha.Text = dtPatient.Rows[0][InfoPatients.PATTEL].ToString();
                this.txtBenhNhan_HoTen.Text = dtPatient.Rows[0][InfoPatients.PATNAME].ToString();
                this.txtBenhNhan_NgheNghiep.Text = dtPatient.Rows[0][InfoPatients.PATOCCUPATION].ToString();
                this.txtBenhNhan_SoID.Text = dtPatient.Rows[0][InfoPatients.PATID].ToString();
                this.spnBenhNhan_Tuoi.EditValue = dtPatient.Rows[0][InfoPatients.PATAGE];
                this.chkBenhNhan_GioiTinh_Nam.EditValue = dtPatient.Rows[0][InfoPatients.PATSEX].ToString();
                this.chkBenhNhan_GioiTinh_Nu.EditValue = dtPatient.Rows[0][InfoPatients.PATSEX].ToString();
            }

            this._dsDynamicTable = this._caseRecordController.getDataDynamicTableDS(this._strCategoryID, this._strPatientID, this._strOtherID1, this._strOtherID2, this._strOtherID3);

            if (this._dsDynamicTable == null)
            {
                this.lblTitle.Text = "";
                this.Text = "Chi Tiết Phẫu Thuật";
                if (this._eDisplayMode == clsEnumType.DisplayMode.STATISTICAL)
                {
                    if (!this._blnFirstLoad)
                        MessageBox.Show(clsConstant.MSG_CaseRecordTree_NotExists);
                    this._strCategoryID = this._strPreCategoryID;
                    this.cboLoaiBieuMau.EditValue = Convert.ToInt32(this._strCategoryID);
                }
                else
                {
                    MessageBox.Show(clsConstant.MSG_CaseRecordTree_NotExists);
                }
                this.dteBenhNhan_NgayPT.Properties.ReadOnly = this.txtBenhNhan_LyDoPT.Properties.ReadOnly = true;
                this.btnSave.Enabled = this.btnDelete.Enabled = false;
                this.btnStatistical.Enabled = (this._strCategoryID != "-1");
                return;
            }
            this._blnFirstLoad = false;
            this._strPreCategoryID = this._strCategoryID;

            this.dteBenhNhan_NgayPT.Properties.ReadOnly = this.txtBenhNhan_LyDoPT.Properties.ReadOnly = false;
            this.btnSave.Enabled = this.btnDelete.Enabled = this.btnStatistical.Enabled = true;
            this._dtCaseRecord_Category = this._dsDynamicTable.Tables[CaseRecord_CategoryInfo.TABLENAME];
            this._strTableName = this._dtCaseRecord_Category.Rows[0][CaseRecord_CategoryInfo.CRC_TABLENAME].ToString();
            this._dtCaseRecord_Tree = this._dsDynamicTable.Tables[CaseRecord_TreeInfo.TABLENAME];
            this._dtCaseRecord_Leaf = this._dsDynamicTable.Tables[CaseRecord_LeafInfo.TABLENAME];
            this._dtDynamicTable = this._dsDynamicTable.Tables[this._strTableName];
            this._drDynamicRow = this._dtDynamicTable.Rows[0];

            this.lblTitle.Text = this.Text = this._dtCaseRecord_Category.Rows[0][CaseRecord_CategoryInfo.HIDDEN_NAME].ToString();
            this.txtBenhNhan_LyDoPT.Text = this._drDynamicRow[clsDynamicTable.Surgical_Reason].ToString();
            this.dteBenhNhan_NgayPT.EditValue = this._drDynamicRow[clsDynamicTable.Surgical_Date];

            _buildTabPages();
        }

        private void _setDisplayControl(clsEnumType.DisplayMode eDisplayMode)
        {
            if (eDisplayMode == clsEnumType.DisplayMode.DATAINPUT)
            {
                this.layoutControl_Delete.Visibility = LayoutVisibility.Always;
                this.layoutControl_Save.Visibility = LayoutVisibility.Always;
                this.layoutControl_Statistical.Visibility = LayoutVisibility.Never;

                this.layTop.Visible = true;
                this.layStatistical.Visible = false;

                DataTable dtPatient = _caseRecordController.getPatientDT(this._strPatientID);
                if (dtPatient.Rows.Count > 0)
                {
                    DataRow drPatient = dtPatient.Rows[0];
                    this.txtBenhNhan_DiaChi.Text = drPatient[InfoPatients.PATADDRESS].ToString();
                    this.txtBenhNhan_DiDong.Text = drPatient[InfoPatients.PATMOBILE].ToString();
                    this.txtBenhNhan_DTnha.Text = drPatient[InfoPatients.PATTEL].ToString();
                    this.txtBenhNhan_HoTen.Text = drPatient[InfoPatients.PATNAME].ToString();
                    this.txtBenhNhan_NgheNghiep.Text = drPatient[InfoPatients.PATOCCUPATION].ToString();
                    this.txtBenhNhan_SoID.Text = drPatient[InfoPatients.PATID].ToString();
                    this.chkBenhNhan_GioiTinh_Nam.EditValue = drPatient[InfoPatients.PATSEX].ToString() == "Nam" ? "1" : "0";
                    this.chkBenhNhan_GioiTinh_Nu.EditValue = drPatient[InfoPatients.PATSEX].ToString() == "Nam" ? "0" : "1";
                    this.spnBenhNhan_Tuoi.EditValue = drPatient[InfoPatients.PATAGE];
                }
                else
                {
                    this.txtBenhNhan_DiaChi.Text = "";
                    this.txtBenhNhan_DiDong.Text = "";
                    this.txtBenhNhan_DTnha.Text = "";
                    this.txtBenhNhan_HoTen.Text = "";
                    this.txtBenhNhan_NgheNghiep.Text = "";
                    this.txtBenhNhan_SoID.Text = "";
                    this.chkBenhNhan_GioiTinh_Nam.EditValue = "0";
                    this.chkBenhNhan_GioiTinh_Nu.EditValue = "1";
                    this.spnBenhNhan_Tuoi.EditValue = 0;
                }
            }
            else if (eDisplayMode == clsEnumType.DisplayMode.PREVIEW)
            {
                this.layoutControl_Delete.Visibility = LayoutVisibility.Never;
                this.layoutControl_Save.Visibility = LayoutVisibility.Never;
                this.layoutControl_Statistical.Visibility = LayoutVisibility.Never;

                this.layTop.Visible = true;
                this.layStatistical.Visible = false;
            }
            else if (eDisplayMode == clsEnumType.DisplayMode.STATISTICAL)
            {
                this.layoutControl_Delete.Visibility = LayoutVisibility.Never;
                this.layoutControl_Save.Visibility = LayoutVisibility.Never;
                this.layoutControl_Statistical.Visibility = LayoutVisibility.Always;

                this.layTop.Visible = false;
                this.layStatistical.Visible = true;

                this.cboLoaiBieuMau.Properties.ValueMember = InfoSurgical.SURISN;
                this.cboLoaiBieuMau.Properties.DisplayMember = InfoSurgical.SURNAME;
                this.cboLoaiBieuMau.Properties.Columns[0].FieldName = InfoSurgical.SURNAME;
                DataTable dtSurgical = _caseRecordController.getSurgicalDT();
                this.cboLoaiBieuMau.Properties.DataSource = dtSurgical;
                if (dtSurgical.Rows.Count > 0)
                {
                    this._strCategoryID = dtSurgical.Rows[0][InfoSurgical.SURISN].ToString();
                    this.cboLoaiBieuMau.EditValue = this._strCategoryID;
                }

                this.chkStatistical_NgayPT.Checked = false;
                this.chkStatistical_NgayPT_EditValueChanged(null, null);
                this.dateStatistical_NgayPT_From.EditValue = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                this.dateStatistical_NgayPT_To.EditValue = DateTime.Today;
                this.txtStatistical_LyDoPT.Text = "";
            }
        }
        #endregion

        #region build controls
        private void _buildTabPages()
        {
            try
            {
                //this.tabMain.TabPages.Clear();
                //LayoutControl myLayoutControl = null;
                //LayoutControlGroup myLayoutControlGroup = null;
                //foreach (DataRow drCaseRecord_Tree in this._dtCaseRecord_Tree.Select(CaseRecord_TreeInfo.CRT_LEVEL + " = 0"))
                //{
                //    _addNewTabPage(myLayoutControl, myLayoutControlGroup, drCaseRecord_Tree);
                //}
                //this.tabMain.SelectedTabPageIndex = 0;
                //_buildControlsOnEachTab((LayoutControl)this.tabMain.TabPages[0].Controls[0], ((LayoutControl)this.tabMain.TabPages[0].Controls[0]).Root);

                this.tabMain.TabPages.Clear();
                LayoutControl myLayoutControl = null;
                LayoutControlGroup myLayoutControlGroup = null;
                DataTable dtNodeTab = this._getNode4BuildTab(_dtCaseRecord_Tree);
                foreach (DataRow drNodeTab in dtNodeTab.Rows)
                {
                    _addNewTabPage(myLayoutControl, myLayoutControlGroup, drNodeTab);
                }
                this.tabMain.SelectedTabPageIndex = 0;
                _buildControlsOnEachTab((LayoutControl)this.tabMain.TabPages[0].Controls[0], ((LayoutControl)this.tabMain.TabPages[0].Controls[0]).Root);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void _buildControlsOnEachTab(LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            this._maxLevel = _getMaxLevel();
            DataRow[] drFoundCaseRecord_LeafArr = null;
            int iCountItem = 0;
            foreach (DataRow drCaseRecord_Tree in this._dtCaseRecord_Tree.Select(CaseRecord_TreeInfo.CRT_BUILDORDER + " >= '" + paramLayoutControl.Tag.ToString() + "'", CaseRecord_TreeInfo.CRT_BUILDORDER))
            {
                if (drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL].ToString() == "0" && drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_BUILDORDER].ToString() != paramLayoutControl.Tag.ToString())
                    break;

                iCountItem++;
                if (iCountItem > clsConstant.NumberItemOnEachTab)
                    break;

                drFoundCaseRecord_LeafArr = this._dtCaseRecord_Leaf.Select(CaseRecord_LeafInfo.CRT_ID + " = '" + drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString() + "'");
                if (drFoundCaseRecord_LeafArr.Length == 0)
                {
                    _addControl_Label(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), paramLayoutControl, paramLayoutControlGroup);
                }
                else
                {
                    if (Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_CONTROLTYPE]) == Convert.ToInt32(clsEnumType.ControlType.CHECKBOX))
                        _addControl_CheckBox(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_COLNAME].ToString(), paramLayoutControl, paramLayoutControlGroup);
                    else if (Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_CONTROLTYPE]) == Convert.ToInt32(clsEnumType.ControlType.NUMERIC))
                        _addControl_Numeric(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_COLNAME].ToString(), paramLayoutControl, paramLayoutControlGroup);
                    else if (Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_CONTROLTYPE]) == Convert.ToInt32(clsEnumType.ControlType.TEXTAREA))
                        _addControl_TextArea(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_MAXLENGTH]), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_COLNAME].ToString(), paramLayoutControl, paramLayoutControlGroup);
                    else if (Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_CONTROLTYPE]) == Convert.ToInt32(clsEnumType.ControlType.RADIOGROUP))
                        _addControl_OptionGroup(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_TITLEFORRADIOGROUP].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_COLNAME].ToString(), paramLayoutControl, paramLayoutControlGroup);
                    else
                        _addControl_TextBox(null, null, drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString(), drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString(), paramLayoutControlGroup.Items.Count, Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]), Convert.ToInt32(drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_MAXLENGTH]), drFoundCaseRecord_LeafArr[0][CaseRecord_LeafInfo.CRL_COLNAME].ToString(), paramLayoutControl, paramLayoutControlGroup);
                }
            }
            _addEmptySpaceItem(paramLayoutControlGroup.Items.Count, paramLayoutControlGroup);
            paramLayoutControl.Refresh();
        }

        private int _getMaxLevel()
        {
            int intLevel = 0;
            foreach (DataRow drCaseRecord_Tree in this._dtCaseRecord_Tree.Rows)
            {
                if (Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]) > intLevel)
                    intLevel = Convert.ToInt32(drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_LEVEL]);
            }
            return intLevel;
        }

        private DataTable _getNode4BuildTab(DataTable dtSource)
        {
            DataTable dtParentNode = dtSource.Clone();
            DataRow drPreParentNode = null;
            int iCountItemOnEachTab = 0;
            int iCountTabRelate = 1;
            int iCurrentRowIndex = -1;

            if (dtSource.Select(CaseRecord_TreeInfo.CRT_LEVEL + " = 0").Length == dtSource.Rows.Count)
            {
                drPreParentNode = dtParentNode.NewRow();
                drPreParentNode[CaseRecord_TreeInfo.CRC_ID] = this._strCategoryID;
                drPreParentNode[CaseRecord_TreeInfo.CRT_BUILDORDER] = 0;
                drPreParentNode[CaseRecord_TreeInfo.CRT_DESCRIPTION] = "";
                drPreParentNode[CaseRecord_TreeInfo.CRT_ID] = this._strCategoryID;
                drPreParentNode[CaseRecord_TreeInfo.CRT_ISLEAF] = 0;
                drPreParentNode[CaseRecord_TreeInfo.CRT_ISUSED] = 0;
                drPreParentNode[CaseRecord_TreeInfo.CRT_LEVEL] = 0;
                drPreParentNode[CaseRecord_TreeInfo.CRT_NAME] = "Thông tin chi tiết";
                drPreParentNode[CaseRecord_TreeInfo.CRT_PARENTID] = this._strCategoryID;
                dtParentNode.Rows.Add(drPreParentNode);
                iCurrentRowIndex++;

                foreach (DataRow drSource in dtSource.Rows)
                {
                    drSource[CaseRecord_TreeInfo.CRT_LEVEL] = 1;
                    if (iCountItemOnEachTab == clsConstant.NumberItemOnEachTab)
                    {
                        dtParentNode.ImportRow(drPreParentNode);
                        iCurrentRowIndex++;
                        iCountTabRelate++;
                        dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_ID] = drPreParentNode[CaseRecord_TreeInfo.CRT_ID].ToString().Trim() + drSource[CaseRecord_TreeInfo.CRT_BUILDORDER].ToString().Trim();
                        dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_LEVEL] = 0;
                        dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_BUILDORDER] = drSource[CaseRecord_TreeInfo.CRT_BUILDORDER];
                        dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_NAME] = drPreParentNode[CaseRecord_TreeInfo.CRT_NAME].ToString().Trim() + " (" + iCountTabRelate + ")";
                        iCountItemOnEachTab = 0;
                    }
                    iCountItemOnEachTab++;
                }
            }
            else
            {
                foreach (DataRow drSource in dtSource.Rows)
                {
                    if (Convert.ToInt32(drSource[CaseRecord_TreeInfo.CRT_LEVEL]) == 0)
                    {
                        dtParentNode.ImportRow(drSource);
                        iCurrentRowIndex++;
                        drPreParentNode = drSource;
                        iCountItemOnEachTab = 0;
                        iCountTabRelate = 1;
                    }
                    else
                    {
                        if (iCountItemOnEachTab == clsConstant.NumberItemOnEachTab)
                        {
                            dtParentNode.ImportRow(drPreParentNode);
                            iCurrentRowIndex++;
                            iCountTabRelate++;
                            dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_ID] = drPreParentNode[CaseRecord_TreeInfo.CRT_ID].ToString().Trim() + drSource[CaseRecord_TreeInfo.CRT_BUILDORDER].ToString().Trim();
                            dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_LEVEL] = 0;
                            dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_BUILDORDER] = drSource[CaseRecord_TreeInfo.CRT_BUILDORDER];
                            dtParentNode.Rows[iCurrentRowIndex][CaseRecord_TreeInfo.CRT_NAME] = drPreParentNode[CaseRecord_TreeInfo.CRT_NAME].ToString().Trim() + " (" + iCountTabRelate + ")";
                            iCountItemOnEachTab = 0;

                        }
                        iCountItemOnEachTab++;
                    }
                }
            }
            return dtParentNode;
        }

        #region TextBox
        private void _addControl_TextBox(TextEdit myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, int intMaxLength, String strDataFieldName, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new TextEdit();
            ((ISupportInitialize)(myControl.Properties)).BeginInit();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_TEXTBOX + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.Properties.MaxLength = intMaxLength;
            myControl.Text = this._drDynamicRow[strDataFieldName].ToString();
            myControl.Tag = strDataFieldName;
            myControl.EditValueChanged += new EventHandler(myTextBox_EditValueChanged);
            ((ISupportInitialize)(myControl.Properties)).EndInit();

            this._addLayoutControlItem(myControl, myLayoutControlItem, strName, strLabel, intIndex, intLevel, paramLayoutControlGroup);
        }

        void myTextBox_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[((TextEdit)sender).Tag.ToString()] = ((TextEdit)sender).Text.Trim();
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }
        #endregion

        #region TextArea
        private void _addControl_TextArea(MemoExEdit myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, int intMaxLength, String strDataFieldName, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new MemoExEdit();
            ((ISupportInitialize)(myControl.Properties)).BeginInit();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_TEXTAREA + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.Properties.AppearanceDropDown.BackColor = Color.LightYellow;
            myControl.Properties.AppearanceDropDown.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.Properties.ShowIcon = false;
            myControl.Properties.WordWrap = true;
            myControl.Properties.Buttons.Add(new EditorButton(ButtonPredefines.Combo));
            myControl.Properties.MaxLength = intMaxLength;
            myControl.QueryPopUp += new CancelEventHandler(myTextArea_QueryPopUp);
            myControl.Text = this._drDynamicRow[strDataFieldName].ToString();
            myControl.Tag = strDataFieldName;
            myControl.EditValueChanged += new EventHandler(myTextArea_EditValueChanged);
            ((ISupportInitialize)(myControl.Properties)).EndInit();

            this._addLayoutControlItem(myControl, myLayoutControlItem, strName, strLabel, intIndex, intLevel, paramLayoutControlGroup);
        }

        void myTextArea_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[((MemoExEdit)sender).Tag.ToString()] = ((MemoExEdit)sender).Text.Trim();
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }

        void myTextArea_QueryPopUp(object sender, CancelEventArgs e)
        {
            ((DevExpress.XtraEditors.MemoExEdit)(sender)).Properties.PopupStartSize = new Size(((DevExpress.XtraEditors.MemoExEdit)(sender)).Width, 100);
        }
        #endregion

        #region Numeric
        private void _addControl_Numeric(SpinEdit myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, String strDataFieldName, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new SpinEdit();
            ((ISupportInitialize)(myControl.Properties)).BeginInit();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_NUMERIC + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.Properties.MaxValue = 999999999999;
            myControl.Properties.Increment = 1;
            myControl.Properties.DisplayFormat.FormatType = FormatType.Numeric;
            myControl.Properties.DisplayFormat.FormatString = "n2";
            myControl.Properties.EditFormat.FormatType = FormatType.Numeric;
            myControl.Properties.EditFormat.FormatString = "n2";
            myControl.Properties.EditMask = "n2";
            myControl.Properties.Mask.EditMask = "n2";
            myControl.Properties.Buttons.Add(new EditorButton(ButtonPredefines.Ellipsis));
            myControl.EditValue = this._drDynamicRow[strDataFieldName];
            myControl.Tag = strDataFieldName;
            myControl.EditValueChanged += new EventHandler(myNumeric_EditValueChanged);
            ((ISupportInitialize)(myControl.Properties)).EndInit();

            this._addLayoutControlItem(myControl, myLayoutControlItem, strName, strLabel, intIndex, intLevel, paramLayoutControlGroup);
        }

        void myNumeric_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[((SpinEdit)sender).Tag.ToString()] = ((SpinEdit)sender).EditValue;
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }
        #endregion

        #region CheckBox
        private void _addControl_CheckBox(CheckEdit myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, String strDataFieldName, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new CheckEdit();
            ((ISupportInitialize)(myControl.Properties)).BeginInit();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_CHECKBOX + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Text = "";
            myControl.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.Properties.ValueChecked = "1";
            myControl.Properties.ValueUnchecked = "0";
            myControl.Properties.NullStyle = StyleIndeterminate.Unchecked;
            myControl.Properties.AutoWidth = true;
            myControl.AutoSizeInLayoutControl = true;
            //myControl.EditValue = this._drDynamicRow[strDataFieldName];
            myControl.EditValue = "1"; //edit by thaoht 20091108
            myControl.Tag = strDataFieldName;
            myControl.EditValueChanged += new EventHandler(myCheckBox_EditValueChanged);
            ((ISupportInitialize)(myControl.Properties)).EndInit();

            this._addLayoutControlItem(myControl, myLayoutControlItem, strName, strLabel, intIndex, intLevel, paramLayoutControlGroup);
        }

        void myCheckBox_EditValueChanged(object sender, EventArgs e)
        {
            this._drDynamicRow[((CheckEdit)sender).Tag.ToString()] = ((CheckEdit)sender).EditValue;
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }
        #endregion

        #region MyRadioGroup
        private void _addControl_OptionGroup(ucMyRadioGroup myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, String strText, int intIndex, int intLevel, String strDataFieldName, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new ucMyRadioGroup();
            ((ISupportInitialize)(myControl.Properties)).BeginInit();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_OPTIONGROUP + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Columns = clsConstant.Radio_Group_ColumnNo;
            myControl.Tag = strDataFieldName;
            myControl.EditValueChanged += new ucMyRadioGroup.EditValueHandler(myRadioGroup_EditValueChanged);
            ((ISupportInitialize)(myControl.Properties)).EndInit();

            this._addLayoutControlItem4RadioGroup(myControl, myLayoutControlItem, strName, strLabel, strText, intIndex, intLevel, paramLayoutControlGroup);
        }

        private void _addLayoutControlItem4RadioGroup(ucMyRadioGroup myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, String strText, int intIndex, int intLevel, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myLayoutControlItem == null)
                myLayoutControlItem = new LayoutControlItem();
            ((ISupportInitialize)(myLayoutControlItem)).BeginInit();
            if (intIndex > 0)
                myLayoutControlItem.Location = new Point(0, paramLayoutControlGroup.Items[intIndex - 1].Y + paramLayoutControlGroup.Items[intIndex - 1].Height);
            else
                myLayoutControlItem.Location = new Point(0, 0);
            paramLayoutControlGroup.Items.AddRange(new BaseLayoutItem[] { myLayoutControlItem });
            myLayoutControlItem.Control = myControl;

            myLayoutControlItem.AppearanceItemCaption.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE, (intLevel == 0 ? FontStyle.Bold : FontStyle.Regular));
            myLayoutControlItem.AppearanceItemCaption.Options.UseFont = true;
            myLayoutControlItem.AppearanceItemCaption.Options.UseTextOptions = true;
            myLayoutControlItem.AppearanceItemCaption.TextOptions.VAlignment = VertAlignment.Top;
            myLayoutControlItem.Name = clsConstant.PREFIX_LAYOUTCONTROLITEM + strName;
            myLayoutControlItem.SizeConstraintsType = SizeConstraintsType.Custom;
            myLayoutControlItem.OptionsToolTip.ToolTip = strLabel;
            for (int i = 0; i < intLevel; i++)
                strLabel = "\t" + strLabel;
            myLayoutControlItem.Text = strLabel;
            myLayoutControlItem.TextLocation = Locations.Left;
            myLayoutControlItem.Padding = new Padding(1, 1, 1, 1);
            myLayoutControlItem.Spacing = new Padding(10, 10, 0, 0);
            if (intIndex % 2 == 0)
                myLayoutControlItem.AppearanceItemCaption.BackColor = Color.Ivory;
            else
                myLayoutControlItem.AppearanceItemCaption.BackColor = Color.Honeydew;

            myControl.DisplayText = strText;
            //myControl.EditValue = this._drDynamicRow[myControl.Tag.ToString()];
            myControl.EditValue = 1; //edit by thaoht 20091108
            int intRowCount = myControl.Count / clsConstant.Radio_Group_ColumnNo;
            if (intRowCount * clsConstant.Radio_Group_ColumnNo < myControl.Count)
                intRowCount++;
            if (intRowCount > 0)
                myLayoutControlItem.MinSize = myLayoutControlItem.Size = new Size(paramLayoutControlGroup.Width - 20, intRowCount * (intRowCount <= 5 ? 25 : 20));
            else
                myLayoutControlItem.MinSize = myLayoutControlItem.Size = new Size(paramLayoutControlGroup.Width - 20, 25);
            ((ISupportInitialize)(myLayoutControlItem)).EndInit();
        }

        void myRadioGroup_EditValueChanged(ucMyRadioGroup sender)
        {
            this._drDynamicRow[sender.Tag.ToString()] = sender.EditValue;
            if (Convert.ToInt32(this._drDynamicRow[DBBaseInfo.Hidden_Status]) != Convert.ToInt32(GlobalEnumType.Status.REGISTER))
                this._drDynamicRow[DBBaseInfo.Hidden_Status] = Convert.ToInt32(GlobalEnumType.Status.UPDATE);
        }
        #endregion

        #region Label & LayoutControlItem
        private void _addControl_Label(LabelControl myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myControl == null)
                myControl = new LabelControl();
            paramLayoutControl.Controls.Add(myControl);
            myControl.Name = clsConstant.PREFIX_LABEL + strName;
            myControl.StyleController = paramLayoutControl;
            myControl.Text = " ";
            myControl.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE);
            myControl.MaximumSize = myControl.MinimumSize = new Size(10, 22);

            this._addLayoutControlItem(myControl, myLayoutControlItem, strName, strLabel, intIndex, intLevel, paramLayoutControlGroup);
        }

        private void _addLayoutControlItem(Control myControl, LayoutControlItem myLayoutControlItem, String strName, String strLabel, int intIndex, int intLevel, LayoutControlGroup paramLayoutControlGroup)
        {
            if (myLayoutControlItem == null)
                myLayoutControlItem = new LayoutControlItem();
            ((ISupportInitialize)(myLayoutControlItem)).BeginInit();
            if (intIndex > 0)
                myLayoutControlItem.Location = new Point(0, paramLayoutControlGroup.Items[intIndex - 1].Y + paramLayoutControlGroup.Items[intIndex - 1].Height);
            else
                myLayoutControlItem.Location = new Point(0, 0);
            paramLayoutControlGroup.Items.AddRange(new BaseLayoutItem[] { myLayoutControlItem });
            if (myControl != null)
            {
                myLayoutControlItem.Control = myControl;
            }

            myLayoutControlItem.AppearanceItemCaption.Font = new System.Drawing.Font(clsConstant.FONT_NAME, clsConstant.FONT_SIZE, (intLevel == 0 ? FontStyle.Bold : FontStyle.Regular));
            myLayoutControlItem.Name = clsConstant.PREFIX_LAYOUTCONTROLITEM + strName;
            myLayoutControlItem.Size = new Size(paramLayoutControlGroup.Width - 10, 30);
            myLayoutControlItem.OptionsToolTip.ToolTip = strLabel;
            for (int i = 0; i < intLevel; i++)
                strLabel = "\t" + strLabel;
            myLayoutControlItem.Text = strLabel;
            myLayoutControlItem.TextLocation = Locations.Left;
            myLayoutControlItem.Padding = new Padding(1, 1, 1, 1);
            myLayoutControlItem.Spacing = new Padding(10, 10, 0, 0);
            if (intIndex % 2 == 0)
                myLayoutControlItem.AppearanceItemCaption.BackColor = Color.Ivory;
            else
                myLayoutControlItem.AppearanceItemCaption.BackColor = Color.Honeydew;
            ((ISupportInitialize)(myLayoutControlItem)).EndInit();
        }
        #endregion

        #region EmptySpaceItem
        private void _addEmptySpaceItem(int intIndex, LayoutControlGroup paramLayoutControlGroup)
        {
            EmptySpaceItem myLayoutControlItem = new EmptySpaceItem();
            ((ISupportInitialize)(myLayoutControlItem)).BeginInit();
            if (intIndex > 0)
                myLayoutControlItem.Location = new Point(0, paramLayoutControlGroup.Items[intIndex - 1].Y + paramLayoutControlGroup.Items[intIndex - 1].Height);
            else
                myLayoutControlItem.Location = new Point(0, 0);
            paramLayoutControlGroup.Items.AddRange(new BaseLayoutItem[] { myLayoutControlItem });
            myLayoutControlItem.Name = "myLayoutControlItemName";
            myLayoutControlItem.Size = new Size(paramLayoutControlGroup.Width - 10, paramLayoutControlGroup.Height - 10);
            ((ISupportInitialize)(myLayoutControlItem)).EndInit();
        }
        #endregion

        #region TabPage
        private void _addNewTabPage(LayoutControl paramLayoutControl, LayoutControlGroup paramLayoutControlGroup, DataRow drCaseRecord_Tree)
        {
            XtraTabPage myXtraTabPage = new XtraTabPage();
            paramLayoutControl = new LayoutControl();
            paramLayoutControlGroup = new LayoutControlGroup();
            ((ISupportInitialize)(paramLayoutControl)).BeginInit();
            ((ISupportInitialize)(paramLayoutControlGroup)).BeginInit();

            myXtraTabPage.SuspendLayout();
            this.tabMain.TabPages.AddRange(new XtraTabPage[] { myXtraTabPage });
            myXtraTabPage.ResumeLayout(false);
            myXtraTabPage.Controls.Add(paramLayoutControl);
            myXtraTabPage.Name = clsConstant.PREFIX_TABPAGE + drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString();
            myXtraTabPage.Size = this.tabMain.Size;
            myXtraTabPage.Text = drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_NAME].ToString();

            paramLayoutControl.Dock = DockStyle.Fill;
            paramLayoutControl.Location = new Point(0, 0);
            paramLayoutControl.Name = clsConstant.PREFIX_LAYOUTCONTROL + drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString();
            paramLayoutControl.Root = paramLayoutControlGroup;
            paramLayoutControl.Size = myXtraTabPage.Size;
            paramLayoutControl.TabIndex = 0;
            paramLayoutControl.Text = " ";
            paramLayoutControl.Tag = drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_BUILDORDER].ToString();

            paramLayoutControlGroup.CustomizationFormText = " ";
            paramLayoutControlGroup.Location = new Point(0, 0);
            paramLayoutControlGroup.Name = clsConstant.PREFIX_LAYOUTCONTROLGROUP + drCaseRecord_Tree[CaseRecord_TreeInfo.CRT_ID].ToString();
            paramLayoutControlGroup.Size = paramLayoutControl.Size;
            paramLayoutControlGroup.Padding = new Padding(0, 0, 10, 0);
            paramLayoutControlGroup.Spacing = new Padding(0, 0, 0, 0);
            paramLayoutControlGroup.Text = " ";
            paramLayoutControlGroup.TextVisible = false;

            ((ISupportInitialize)(paramLayoutControl)).EndInit();
            ((ISupportInitialize)(paramLayoutControlGroup)).EndInit();
        }

        private void tabMain_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            try
            {
                if (e.Page != null)
                {
                    if (e.Page.Controls.Count > 0)
                    {
                        if (((LayoutControl)e.Page.Controls[0]).Root.Items.Count <= 0)
                            _buildControlsOnEachTab((LayoutControl)e.Page.Controls[0], ((LayoutControl)e.Page.Controls[0]).Root);
                    }
                }
            }
            catch (Exception ex) { Class.ShowException(ex); }
        }
        #endregion
        #endregion
    }
}